class ReportTemplate < ActiveRecord::Base
  belongs_to :ticket_template
  has_and_belongs_to_many :note_types, :order => "priority"
  validates_presence_of   :name
  validates_length_of     :name,  :within => 1..255
  validates_uniqueness_of :name
  serialize :selected_main_fields
  serialize :conditions_fields
  serialize :conditions_signs
  attr_protected :conditions_fields
  attr_protected :conditions_signs
  validates_presence_of :order
  validates_inclusion_of :order, :in => ["created_at", "updated_at", "deadline", "created_at DESC", "updated_at DESC", "deadline DESC"]

  def conditions
    if self.conditions_fields
      i = -1
      self.conditions_fields.map{ |field|
        i += 1
        {:field => field, :sign => self.conditions_signs[i] }
      }
    else
      []
    end
  end

  def conditions=(cond)
    self.conditions_fields = []
    self.conditions_signs = []
    cond.each {|condition|
      self.conditions_fields << condition[:field]
      self.conditions_signs << condition[:sign]
    }
  end

  def validate
    conditions.each {|condition|
      if !(["created_at", "deadline", "updated_at"].include? condition[:field]) || !(["<", ">"].include? condition[:sign])
        errors.add(:conditions, "Conditions are not valid (#{condition[:field]} , #{condition[:sign]})")
      end
    }
  end

end
